//
//  WUNavigationController.m
//  bestkeep
//
//  Created by 武探 on 2016/12/14.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "WUNavigationController.h"

#define WUNavigationControllerAllowDragMaxX 40.0

@interface WUNavigationController ()<UIGestureRecognizerDelegate>

@property(nonatomic,strong) UIView *backgroundView;
@property(nonatomic,strong) UIView *backgroundMask;
@property(nonatomic,strong) UIImageView *screenShotImageView;
@property(nonatomic,strong) NSMutableArray<UIImage*> *screenShotsArray;
@property(nonatomic,assign) BOOL isMoving;
@property(nonatomic,assign) CGPoint startTouchPoint;

@end

@implementation WUNavigationController

-(instancetype)init {
    self = [super init];
    if(self) {
        self.allowBackGestureRecognizer = YES;
    }
    return self;
}

-(instancetype)initWithRootViewController:(UIViewController *)rootViewController {
    self = [super initWithRootViewController:rootViewController];
    if(self) {
        self.allowBackGestureRecognizer = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.interactivePopGestureRecognizer.enabled = false;
    
    _screenShotsArray = [NSMutableArray array];
    
    UIImageView *shadowImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"WUNavigationBackgroundShadow"]];
    shadowImageView.frame = CGRectMake(-10, 0, 10, CGRectGetHeight(self.view.frame));
    [self.view addSubview:shadowImageView];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
    pan.delegate = self;
    pan.delaysTouchesBegan = YES;
    [self.view addGestureRecognizer:pan];
}

-(UIImage*)capture {
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated {
    [_screenShotsArray addObject:[self capture]];
    [super pushViewController:viewController animated:animated];
}

-(UIViewController *)popViewControllerAnimated:(BOOL)animated {
    [_screenShotsArray removeLastObject];
    return [super popViewControllerAnimated:animated];
}

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    if(keyWindow == nil) {
        return NO;
    }
    if(self.viewControllers.count <= 1 || !self.allowBackGestureRecognizer) {
        return NO;
    }
    
    CGPoint touchPoint = [gestureRecognizer locationInView:keyWindow];
    if(touchPoint.x > WUNavigationControllerAllowDragMaxX) {
        return NO;
    }
    return YES;
}

-(void)panGestureRecognizer:(UIGestureRecognizer*)gestureRecognizer {
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGPoint touchPoint = [gestureRecognizer locationInView:keyWindow];
    
    UIGestureRecognizerState state = gestureRecognizer.state;
    
    switch (state) {
        case UIGestureRecognizerStateBegan: {
            _startTouchPoint = touchPoint;
            _isMoving = true;
            if(_backgroundView == nil) {
                CGRect frame = self.view.bounds;
                _backgroundView = [[UIView alloc] initWithFrame:frame];
                [self.view.superview insertSubview:_backgroundView belowSubview:self.view];
                _backgroundMask = [[UIView alloc] initWithFrame:_backgroundView.bounds];
                _backgroundMask.backgroundColor = [UIColor blackColor];
                [_backgroundView addSubview:_backgroundMask];
                
            }
            
            _backgroundView.hidden = NO;
            
            if(_screenShotImageView != nil) {
                [_screenShotImageView removeFromSuperview];
                _screenShotImageView = nil;
            }
            
            UIImage *image = _screenShotsArray.lastObject;
            _screenShotImageView = [[UIImageView alloc] initWithImage:image];
            [_backgroundView addSubview:_screenShotImageView];
        }
            break;
        case UIGestureRecognizerStateEnded: {
            CGRect screenBounds = [[UIScreen mainScreen] bounds];
            if(touchPoint.x - self.startTouchPoint.x > screenBounds.size.width / 3) {
                [UIView animateWithDuration:0.3 animations:^{
                    [self moveViewWithX:screenBounds.size.width];
                } completion:^(BOOL finished) {
                    [self popViewControllerAnimated:NO];
                    CGRect frame = self.view.frame;
                    frame.origin.x = 0;
                    self.view.frame = frame;
                    
                    self.isMoving = NO;
                }];
                
            } else {
                [self endAnimate];
            }
        }
            break;
        case UIGestureRecognizerStateCancelled: {
            [self endAnimate];
        }
            break;
        default: {
            if(self.isMoving) {
                [self moveViewWithX:touchPoint.x - self.startTouchPoint.x];
            }
        }
            break;
    }
}

-(void)endAnimate {
    [UIView animateWithDuration:0.3 animations:^{
        [self moveViewWithX:0];
    } completion:^(BOOL finished) {
        self.isMoving = NO;
        self.backgroundView.hidden = YES;
    }];
}

/**
 移动当前控制器的View
 
 - parameter currentX: 当前控制器View即将运动的X（终点）
 */
-(void)moveViewWithX:(CGFloat)x {
    
    CGFloat width = [[UIScreen mainScreen] bounds].size.width;
    x = x > width ? width : x;
    x = x < 0 ? 0 : x;
    
    CGRect frame = self.view.frame;
    frame.origin.x = x;
    self.view.frame = frame;
    
    CGFloat scale = x / 6400 + 0.95;
    CGFloat alpha = 0.4 - x / 800;
    _screenShotImageView.transform = CGAffineTransformMakeScale(scale, scale);
    _backgroundMask.alpha = alpha;
}


@end
